package com.leadership.api.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.persistence.annotation.Dao;
import com.leadership.api.dao.CourseLearningDao;
import com.leadership.api.dao.UserDao;
import com.leadership.api.dao.UserProjectDao;
import com.leadership.api.service.CertificateService;
import com.leadership.entity.Constant;
import com.leadership.entity.certificate.Certificate;
import com.leadership.entity.certificate.CertificateRecord;
import com.leadership.entity.course.CourseLearning;
import com.leadership.entity.project.UserProject;
import com.leadership.entity.user.User;
import com.leadership.training.entity.project.ProjectTrainee;
import com.leadership.training.entity.project.TrainingResult;

/**
 * 
 * @author mohanlan
 *
 */
@Service("certificateService")
public class CertificateServiceImpl implements CertificateService {
    
    private static final Logger logger = LoggerFactory.getLogger(CertificateServiceImpl.class);
    
    @Autowired
    private GenericDaoSupport genericDaoSupport;
    
    @Dao
    private UserProjectDao userProjectDao;
    
    @Dao
    private UserDao userDao;
    
    @Dao
    private CourseLearningDao courseLearningDao;
    
    /*
     * (non-Javadoc)
     * @see com.leadership.api.service.CertificateService#updateCertificate()
     */
    @SuppressWarnings("unchecked")
    public void updateCertificate() {
        
        
        
        List<Long> ids = new ArrayList<Long>();
        ids.add(15L);
        ids.add(16L);
        String sentence = "FROM ProjectTrainee pt WHERE pt.syncedCertificated = false AND pt.disabled = false AND pt.complete = true AND pt.project.secondCategory.id in (:ids)";
        List<ProjectTrainee> projectTrainees = genericDaoSupport.searchForList(sentence, "ids", ids);
        
        logger.info("get projectTrainees size ");
        
        List<Certificate> certificates = genericDaoSupport.loadAll(Certificate.class);
        
        if(projectTrainees != null && projectTrainees.size() > 0) {
            
            logger.info("get projectTrainees not empty");
            
            for(ProjectTrainee projectTrainee : projectTrainees) {
                if(projectTrainee.getComplete()) {
                    
                    String email = projectTrainee.getTrainee().getEmail();
                    User user = userDao.load(email);
//                    logger.info("get projectTrainees user is [{}]", email);
                    
                    if(user != null) {
                        logger.info("get user is [{}]", user.getId());
                        
                        projectTrainee.setSyncedCertificated(true);
                        genericDaoSupport.update(projectTrainee);
                        
                        for(Certificate certificate : certificates) {
                            CertificateRecord certificateRecord = new CertificateRecord(user, certificate, new Date(), user.getCurrentProjectId());
                            genericDaoSupport.save(certificateRecord);
                        }
                        
                        UserProject userProject = userProjectDao.load(user, user.getCurrentProjectId());
                        userProject.setCertificateCompleted(true);
                        genericDaoSupport.update(userProject);
                        
                    }
                    
                }
            }
            
        }
        
    }
    
    @SuppressWarnings("unchecked")
    public void updateOutCourse() {
        
        List<Long> ids = new ArrayList<Long>();
        ids.add(15L);
        ids.add(16L);
        ids.add(17L);
        
        List<Long> phase15Ids = genericDaoSupport.searchForList("SELECT projectPhase.id FROM ProjectPhaseCourse WHERE disabled = false AND course.id in (15)");
        List<Long> phase16Ids = genericDaoSupport.searchForList("SELECT projectPhase.id FROM ProjectPhaseCourse WHERE disabled = false AND course.id in (16)");
        List<Long> phase17Ids = genericDaoSupport.searchForList("SELECT projectPhase.id FROM ProjectPhaseCourse WHERE disabled = false AND course.id in (17)");
        
        List<TrainingResult> trainingResults15 = genericDaoSupport.searchForList("FROM TrainingResult WHERE projectPhase.id in (:ids)", "ids", phase15Ids);
        List<TrainingResult> trainingResults16 = genericDaoSupport.searchForList("FROM TrainingResult WHERE projectPhase.id in (:ids)", "ids", phase16Ids);
        List<TrainingResult> trainingResults17 = genericDaoSupport.searchForList("FROM TrainingResult WHERE projectPhase.id in (:ids)", "ids", phase17Ids);
        
        for(TrainingResult trainingResult : trainingResults15) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("traineeId", trainingResult.getTrainee().getId());
            params.put("projectId", trainingResult.getProjectPhase().getProject().getId());
            ProjectTrainee projectTrainee = genericDaoSupport.searchForObject("FROM ProjectTrainee Where trainee.id = :traineeId AND project.id = :projectId AND complete = true AND disabled = false", params, ProjectTrainee.class);
            if(projectTrainee != null) {
                String email = projectTrainee.getTrainee().getEmail();
                List<CourseLearning> courseLearnings = courseLearningDao.list(email, "15");
                for(CourseLearning courseLearning : courseLearnings) {
                    logger.info("update courselearning  user[{}] projectId[{}]", courseLearning.getUser().getEmail(), courseLearning.getProjectId());
                    genericDaoSupport.update(courseLearning.update(true, null));
                    
                    UserProject userProject = userProjectDao.load(courseLearning.getUser(), courseLearning.getProjectId());
                    if(userProject != null) {
                      if(courseLearning.getCourse().getId().equals(Constant.REQUIRED_COURSE_ONE_ID)) {
                          userProject.setRequiredCourseOneCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.REQUIRED_COURSE_TWO_ID)) {
                          userProject.setRequiredCourseTwoCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.REQUIRED_COURSE_THREE_ID)) {
                          userProject.setRequiredCourseThreeCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.REQUIRED_COURSE_FOUR_ID)) {
                          userProject.setRequiredCourseFourCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.OPTIONAL_COURSE_ONE_ID)) {
                          userProject.setOptionalCourseOneCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.OPTIONAL_COURSE_TWO_ID)) {
                          userProject.setOptionalCourseTwoCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.OPTIONAL_COURSE_THREE_ID)) {
                          userProject.setOptionalCourseThreeCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.OPTIONAL_COURSE_FOUR_ID)) {
                          userProject.setOptionalCourseFourCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.OPTIONAL_COURSE_FIVE_ID)) {
                          userProject.setOptionalCourseFiveCompleted(true);
                      }
                   }
                    
                }
            }
        }
        
        for(TrainingResult trainingResult : trainingResults16) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("traineeId", trainingResult.getTrainee().getId());
            params.put("projectId", trainingResult.getProjectPhase().getProject().getId());
            ProjectTrainee projectTrainee = genericDaoSupport.searchForObject("FROM ProjectTrainee Where trainee.id = :traineeId AND project.id = :projectId AND complete = true AND disabled = false", params, ProjectTrainee.class);
            if(projectTrainee != null) {
                String email = projectTrainee.getTrainee().getEmail();
                List<CourseLearning> courseLearnings = courseLearningDao.list(email, "16");
                for(CourseLearning courseLearning : courseLearnings) {
                    genericDaoSupport.update(courseLearning.update(true, null));
                    
                    UserProject userProject = userProjectDao.load(courseLearning.getUser(), courseLearning.getProjectId());
                    if(userProject != null) {
                      if(courseLearning.getCourse().getId().equals(Constant.REQUIRED_COURSE_ONE_ID)) {
                          userProject.setRequiredCourseOneCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.REQUIRED_COURSE_TWO_ID)) {
                          userProject.setRequiredCourseTwoCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.REQUIRED_COURSE_THREE_ID)) {
                          userProject.setRequiredCourseThreeCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.REQUIRED_COURSE_FOUR_ID)) {
                          userProject.setRequiredCourseFourCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.OPTIONAL_COURSE_ONE_ID)) {
                          userProject.setOptionalCourseOneCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.OPTIONAL_COURSE_TWO_ID)) {
                          userProject.setOptionalCourseTwoCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.OPTIONAL_COURSE_THREE_ID)) {
                          userProject.setOptionalCourseThreeCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.OPTIONAL_COURSE_FOUR_ID)) {
                          userProject.setOptionalCourseFourCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.OPTIONAL_COURSE_FIVE_ID)) {
                          userProject.setOptionalCourseFiveCompleted(true);
                      }
                   }
                }
            }
        }
        
        for(TrainingResult trainingResult : trainingResults17) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("traineeId", trainingResult.getTrainee().getId());
            params.put("projectId", trainingResult.getProjectPhase().getProject().getId());
            ProjectTrainee projectTrainee = genericDaoSupport.searchForObject("FROM ProjectTrainee Where trainee.id = :traineeId AND project.id = :projectId AND complete = true AND disabled = false", params, ProjectTrainee.class);
            if(projectTrainee != null) {
                String email = projectTrainee.getTrainee().getEmail();
                List<CourseLearning> courseLearnings = courseLearningDao.list(email, "17");
                for(CourseLearning courseLearning : courseLearnings) {
                    genericDaoSupport.update(courseLearning.update(true, null));
                    
                    UserProject userProject = userProjectDao.load(courseLearning.getUser(), courseLearning.getProjectId());
                    if(userProject != null) {
                      if(courseLearning.getCourse().getId().equals(Constant.REQUIRED_COURSE_ONE_ID)) {
                          userProject.setRequiredCourseOneCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.REQUIRED_COURSE_TWO_ID)) {
                          userProject.setRequiredCourseTwoCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.REQUIRED_COURSE_THREE_ID)) {
                          userProject.setRequiredCourseThreeCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.REQUIRED_COURSE_FOUR_ID)) {
                          userProject.setRequiredCourseFourCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.OPTIONAL_COURSE_ONE_ID)) {
                          userProject.setOptionalCourseOneCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.OPTIONAL_COURSE_TWO_ID)) {
                          userProject.setOptionalCourseTwoCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.OPTIONAL_COURSE_THREE_ID)) {
                          userProject.setOptionalCourseThreeCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.OPTIONAL_COURSE_FOUR_ID)) {
                          userProject.setOptionalCourseFourCompleted(true);
                          genericDaoSupport.update(userProject);
                      } else if(courseLearning.getCourse().getId().equals(Constant.OPTIONAL_COURSE_FIVE_ID)) {
                          userProject.setOptionalCourseFiveCompleted(true);
                      }
                   }
                    
                }
            }
        }
        
    }
    
    /*
     * (non-Javadoc)
     * @see com.leadership.api.service.CertificateService#updateUserProject()
     */
    @SuppressWarnings("unchecked")
    public void updateUserProject() {
        
        String sentence = "FROM CourseLearning WHERE completed = true";
        List<CourseLearning> courseLearnings = genericDaoSupport.searchForList(sentence);
        
        for(CourseLearning courseLearning : courseLearnings) {
            UserProject userProject = userProjectDao.load(courseLearning.getUser(), courseLearning.getProjectId());
            if(userProject != null) {
              if(courseLearning.getCourse().getId().equals(Constant.REQUIRED_COURSE_ONE_ID)) {
                  userProject.setRequiredCourseOneCompleted(true);
                  genericDaoSupport.update(userProject);
              } else if(courseLearning.getCourse().getId().equals(Constant.REQUIRED_COURSE_TWO_ID)) {
                  userProject.setRequiredCourseTwoCompleted(true);
                  genericDaoSupport.update(userProject);
              } else if(courseLearning.getCourse().getId().equals(Constant.REQUIRED_COURSE_THREE_ID)) {
                  userProject.setRequiredCourseThreeCompleted(true);
                  genericDaoSupport.update(userProject);
              } else if(courseLearning.getCourse().getId().equals(Constant.REQUIRED_COURSE_FOUR_ID)) {
                  userProject.setRequiredCourseFourCompleted(true);
                  genericDaoSupport.update(userProject);
              } else if(courseLearning.getCourse().getId().equals(Constant.OPTIONAL_COURSE_ONE_ID)) {
                  userProject.setOptionalCourseOneCompleted(true);
                  genericDaoSupport.update(userProject);
              } else if(courseLearning.getCourse().getId().equals(Constant.OPTIONAL_COURSE_TWO_ID)) {
                  userProject.setOptionalCourseTwoCompleted(true);
                  genericDaoSupport.update(userProject);
              } else if(courseLearning.getCourse().getId().equals(Constant.OPTIONAL_COURSE_THREE_ID)) {
                  userProject.setOptionalCourseThreeCompleted(true);
                  genericDaoSupport.update(userProject);
              } else if(courseLearning.getCourse().getId().equals(Constant.OPTIONAL_COURSE_FOUR_ID)) {
                  userProject.setOptionalCourseFourCompleted(true);
                  genericDaoSupport.update(userProject);
              } else if(courseLearning.getCourse().getId().equals(Constant.OPTIONAL_COURSE_FIVE_ID)) {
                  userProject.setOptionalCourseFiveCompleted(true);
              }
           }
        }
        
        List<CertificateRecord> certificateRecords = genericDaoSupport.loadAll(CertificateRecord.class);
        for(CertificateRecord certificateRecord : certificateRecords) {
            UserProject userProject = userProjectDao.load(certificateRecord.getUser(), certificateRecord.getCurrentProjectId());
            if(userProject != null) {
                userProject.setCertificateCompleted(true);
                genericDaoSupport.update(userProject);
            }
        }
    }
}
